package com.gzdh.device.thir.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzdh.device.comm.vo.Result;
import com.gzdh.device.config.annotation.IgnoreAuthorize;
import com.gzdh.device.shop.entity.TradeNo;
import com.gzdh.device.shop.model.BillModel;
import com.gzdh.device.shop.service.TradeNoService;
import com.gzdh.device.wx.entity.WxSubMchid;
import com.gzdh.device.wx.service.WxSubMchidService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.gzdh.device.comm.util.ThirSignUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("api/thir/bill/v1")
public class ThirBillController {
    @Autowired
    TradeNoService tradeNoService;
    @Autowired
    WxSubMchidService wxSubMchidService;

    @PostMapping("downBill")
    @IgnoreAuthorize
    public ResponseEntity<Result<Object>> downBill(@RequestParam("merchant") String merchant,
                                                   @RequestParam("date") String date, HttpServletRequest request, HttpServletResponse response) {
        Result<Object> result = new Result<>();
        if (!ThirSignUtil.thirSign(request)) {
            return ResponseEntity.status(403).body(Result.error(403, "认证失败"));
        }
        List<TradeNo> tradeNoList = tradeNoService.list(new QueryWrapper<TradeNo>().lambda().eq(TradeNo::getMerchant, merchant)
                .ge(TradeNo::getTransactionTime, date + " 00:00:00").le(TradeNo::getTransactionTime, date + " 23:59:59"));
        result.setResult(tradeNoList);
        return ResponseEntity.status(200).body(result);
    }


    @PostMapping("findBill")
    @IgnoreAuthorize
    public ResponseEntity<Result<Object>> findBill(@RequestParam(name = "merchant", required = false) String merchant,
                                                   @RequestParam(name = "startTime", required = false) String startTime,
                                                   @RequestParam(name = "endTime", required = false) String endTime,
                                                   HttpServletRequest request) {
        Result<Object> result = new Result<>();

        if (!ThirSignUtil.thirSign(request)) {
            return ResponseEntity.status(403).body(Result.error(403, "认证失败"));
        }
        List<WxSubMchid> wxSubMchidList = wxSubMchidService.list();
        List<String> stringList = new ArrayList<>();
        for (WxSubMchid goo : wxSubMchidList) {
            stringList.add(goo.getMerchant());
        }
        List<TradeNo> tradeNoList = new ArrayList<>();
        if (StringUtils.isEmpty(merchant)) {
            Date date = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.DATE, -1);
            date = calendar.getTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            startTime = sdf.format(date);
            endTime = sdf.format(date);
        }

        tradeNoList = tradeNoService.list(new QueryWrapper<TradeNo>().lambda().eq(StringUtils.isNotEmpty(merchant), TradeNo::getMerchant, merchant)
                .ge(TradeNo::getTransactionTime, startTime + " 00:00:00").le(TradeNo::getTransactionTime, endTime + " 23:59:59")
                .in(TradeNo::getMerchant, stringList)
                .orderByDesc(TradeNo::getTransactionTime));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<BillModel> billModelList = new ArrayList<>();

        for (TradeNo goo : tradeNoList) {
            BillModel billModel = billModelList.stream()
                    .filter(billModel1 -> sdf.format(goo.getTransactionTime()).equals(billModel1.getDate()))
                    .filter(billModel1 -> billModel1.getMerchant().equals(goo.getMerchant()))
                    .findFirst().orElse(null);
            if (billModel == null) {
                billModel = new BillModel();
                billModel.setMerchant(goo.getMerchant());
                WxSubMchid wxSubMchid = wxSubMchidList.stream().filter(wxSubMchid1 -> wxSubMchid1.getMerchant().equals(goo.getMerchant())).findFirst().orElse(null);
                billModel.setShopName(wxSubMchid != null ? wxSubMchid.getName() : "未知");
                billModel.setPayPrice(new BigDecimal(0));
                billModel.setRefundPrice(new BigDecimal(0));
                billModel.setWxPrice(new BigDecimal(0));
                billModel.setZfbPrice(new BigDecimal(0));
                billModel.setPaidAmount(new BigDecimal(0));
                billModel.setRatePrice(new BigDecimal(0));
                billModel.setSettlement(new BigDecimal(0));
                billModel.setDate(sdf.format(goo.getTransactionTime()));
                if ("进账".equals(goo.getCapitalFlow())) {
                    billModel.setPayPrice(new BigDecimal(goo.getPayPrice()).divide(new BigDecimal(100)));
                    if ("微信支付".equals(goo.getPaymentMethod())) {
                        billModel.setWxPrice(new BigDecimal(goo.getPayPrice()).divide(new BigDecimal(100)));
                        billModel.setWxPayCounts(billModel.getWxPayCounts() + 1);
                    } else if ("支付宝支付".equals(goo.getPaymentMethod())) {
                        billModel.setZfbPrice(new BigDecimal(goo.getPayPrice()).divide(new BigDecimal(100)));
                        billModel.setZfbPayCounts(billModel.getZfbPayCounts() + 1);
                    }
                    billModel.setPayCounts(billModel.getPayCounts() + 1);
                    billModel.setPaidAmount(billModel.getPaidAmount().add(new BigDecimal(goo.getPayPrice()).divide(new BigDecimal(100))));
                    billModel.setRatePrice(billModel.getRatePrice().add(new BigDecimal(goo.getCommission()).divide(new BigDecimal(100))));
                    billModel.setSettlement(billModel.getSettlement().add(new BigDecimal(goo.getSettlement()).divide(new BigDecimal(100))));
                } else {
                    billModel.setRefundPrice(new BigDecimal(goo.getPayPrice()).divide(new BigDecimal(100)));
                    billModel.setPaidAmount(billModel.getPaidAmount().subtract(new BigDecimal(goo.getPayPrice()).divide(new BigDecimal(100))));
                    billModel.setRatePrice(billModel.getRatePrice().subtract(new BigDecimal(goo.getCommission()).divide(new BigDecimal(100))));
                    billModel.setSettlement(billModel.getSettlement().subtract(new BigDecimal(goo.getSettlement()).divide(new BigDecimal(100))));
                }

                billModelList.add(billModel);
            } else {
                if ("进账".equals(goo.getCapitalFlow())) {
                    billModel.setPayPrice(billModel.getPayPrice().add(new BigDecimal(goo.getPayPrice()).divide(new BigDecimal(100))));
                    if ("微信支付".equals(goo.getPaymentMethod())) {
                        billModel.setWxPrice(billModel.getWxPrice().add(new BigDecimal(goo.getPayPrice()).divide(new BigDecimal(100))));
                        billModel.setWxPayCounts(billModel.getWxPayCounts() + 1);
                    } else if ("支付宝支付".equals(goo.getPaymentMethod())) {
                        billModel.setZfbPrice(billModel.getZfbPrice().add(new BigDecimal(goo.getPayPrice()).divide(new BigDecimal(100))));
                        billModel.setZfbPayCounts(billModel.getZfbPayCounts() + 1);
                    }
                    billModel.setPayCounts(billModel.getPayCounts() + 1);
                    billModel.setPaidAmount(billModel.getPaidAmount().add(new BigDecimal(goo.getPayPrice()).divide(new BigDecimal(100))));
                    billModel.setRatePrice(billModel.getRatePrice().add(new BigDecimal(goo.getCommission()).divide(new BigDecimal(100))));
                    billModel.setSettlement(billModel.getSettlement().add(new BigDecimal(goo.getSettlement()).divide(new BigDecimal(100))));
                } else {
                    billModel.setRefundPrice(billModel.getRefundPrice().add(new BigDecimal(goo.getPayPrice()).divide(new BigDecimal(100))));
                    billModel.setPaidAmount(billModel.getPaidAmount().subtract(new BigDecimal(goo.getPayPrice()).divide(new BigDecimal(100))));
                    billModel.setRatePrice(billModel.getRatePrice().subtract(new BigDecimal(goo.getCommission()).divide(new BigDecimal(100))));
                    billModel.setSettlement(billModel.getSettlement().subtract(new BigDecimal(goo.getSettlement()).divide(new BigDecimal(100))));
                }
            }
        }
        result.setResult(billModelList);
        return ResponseEntity.status(200).body(result);
    }
}
